package com.xnyzc.lhy.mis.service.impl.cms.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.xnyzc.lhy.common.component.config.GlobalConfig;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.exception.PangException;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.order.ELoginFlag;
import com.xnyzc.lhy.common.util.*;
import com.xnyzc.lhy.mis.entity.area.OaSysArea;
import com.xnyzc.lhy.mis.entity.area.OaSysOpenArea;
import com.xnyzc.lhy.mis.entity.cms.OaSysRole;
import com.xnyzc.lhy.mis.entity.dictionaries.OaSysDict;
import com.xnyzc.lhy.mis.entity.param.cms.OfficeParam;
import com.xnyzc.lhy.mis.entity.param.cms.UpdateOfficeParam;
import com.xnyzc.lhy.mis.entity.param.cms.user.SupplierSeparateAccountParam;
import com.xnyzc.lhy.mis.entity.param.cms.user.SysDriverManagerParam;
import com.xnyzc.lhy.mis.entity.param.cms.user.SysUserParam;
import com.xnyzc.lhy.mis.entity.result.cms.SysUserResults;
import com.xnyzc.lhy.mis.entity.result.cms.role.UserCityResult;
import com.xnyzc.lhy.mis.entity.result.cms.role.UserLevelResult;
import com.xnyzc.lhy.mis.entity.result.cms.role.UserRoleResult;
import com.xnyzc.lhy.mis.entity.result.office.DUserInfoResult;
import com.xnyzc.lhy.mis.entity.result.user.OaSysUserManagersRes;
import com.xnyzc.lhy.mis.entity.result.user.UserResult;
import com.xnyzc.lhy.mis.entity.sidebar.OaCUserOffice;
import com.xnyzc.lhy.mis.entity.sidebar.OaSysOffice;
import com.xnyzc.lhy.mis.entity.system.*;
import com.xnyzc.lhy.mis.entity.user.*;
import com.xnyzc.lhy.mis.mapper.area.OaSysAreaMapper;
import com.xnyzc.lhy.mis.mapper.area.OaSysOpenAreaMapper;
import com.xnyzc.lhy.mis.mapper.cms.OaSysRoleMapper;
import com.xnyzc.lhy.mis.mapper.dictionaries.OaSysDictMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaCUserOfficeMapper;
import com.xnyzc.lhy.mis.mapper.sidebar.OaSysOfficeMapper;
import com.xnyzc.lhy.mis.mapper.system.*;
import com.xnyzc.lhy.mis.mapper.user.*;
import com.xnyzc.lhy.mis.service.cms.office.OfficeService;
import com.xnyzc.lhy.mis.service.cms.user.SysUserService;
import com.xnyzc.lhy.mis.service.cms.util.IOfficeUtilService;
import com.xnyzc.lhy.mis.service.impl.cms.office.OfficeServiceImpl;
import com.xnyzc.lhy.mis.service.impl.cms.util.OaSysGetOfficeIdListServiceImpl;
import com.xnyzc.lhy.mis.service.impl.order.OaDOrderCorrelationServiceImpl;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;

/**
 * <p>
 * 用户管理相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-08-08
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private OaSysUserMapper oaSysUserMapper;

    @Autowired
    private OfficeServiceImpl officeServiceImpl;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private OaCUserMapper oaCUserMapper;

    @Autowired
    private OaCUserInfoMapper oaCUserInfoMapper;

    @Autowired
    private OaDUserInfoMapper oaDUserInfoMapper;

    @Autowired
    private OaDOrderCorrelationServiceImpl oaDOrderCorrelationServiceImpl;

    @Autowired
    private OaCUserOfficeMapper oaCUserOfficeMapper;

    @Autowired
    private OaDUserOfficeMapper oaDUserOfficeMapper;

    @Autowired
    private OaSysOfficeMapper oaSysOfficeMapper;

    @Autowired
    private OaSysDictMapper oaSysDictMapper;

    @Autowired
    private OaSysUserRoleMapper oaSysUserRoleMapper;

    @Autowired
    private IOfficeUtilService iOfficeUtilService;

    @Autowired
    private OaSysUserOfficeMapper oaSysUserOfficeMapper;

    @Autowired
    private OaSysRoleMapper oaSysRoleMapper;

    @Autowired
    private OaSysUserCityMapper oaSysUserCityMapper;

    @Autowired
    private OaSysAreaMapper oaSysAreaMapper;

    @Autowired
    private OaSysOpenAreaMapper oaSysOpenAreaMapper;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private OaSysGetOfficeIdListServiceImpl oaSysGetOfficeIdListService;

    @Autowired
    private OaSysUserSeparateAccountMapper oaSysUserSeparateAccountMapper;
    /**
     * 获取系统用户管理列表
     *
     * @return
     */
    @Override
    public Rv getSysUserList(OfficeParam officeParam) {
        Integer current = officeParam.getCurrent();
        Integer pageSize = officeParam.getPageSize();
        if (CheckUtil.objIsEmpty(current, pageSize)) {
            throw PangException.create(EErrorCode.missingArg);
        }
        Long userId = TokenUtil.getTokenUserId();
        OaSysUser user = oaSysUserMapper.selectById(userId);
        // 生成数据权限过滤条件（dsf为dataScopeFilter的简写，在xml中使用 ${sqlMap.dsf}调用权限SQL）
        GlobalConfig config = new GlobalConfig();
        config.getSqlMap().put("dsf", officeServiceImpl.dataScopeFilter(user, "o", "a"));
        if (StringUtils.isNotEmpty(officeParam.getLoginName())) {
            config.setLoginName(officeParam.getLoginName());
        }
        if (CheckUtil.objIsNotEmpty(officeParam.getOfficeId())) {
            config.setOfficeId(officeParam.getOfficeId());
        }
        if (StringUtils.isNotEmpty(officeParam.getMobile())) {
            config.setMobile(officeParam.getMobile());
        }
        if (CheckUtil.objIsNotEmpty(officeParam.getRoleId())) {
            config.setRoleId(officeParam.getRoleId());
        }
        if (StringUtils.isNotEmpty(officeParam.getBusinessModule())) {
            config.setBusinessModule(officeParam.getBusinessModule());
        }
        if (StringUtils.isNotEmpty(officeParam.getBusinessType())) {
            config.setBusinessType(officeParam.getBusinessType());
        }
        if (StringUtils.isNotEmpty(officeParam.getLoginFlag())) {
            config.setLoginFlag(officeParam.getLoginFlag());
        }
        if (StringUtils.isNotEmpty(officeParam.getCityCode())) {
            config.setCityCode(officeParam.getCityCode());
        }
        List collectionList = oaSysUserMapper.sysUserList(config);
        config.setPage(Long.valueOf((current - 1) * pageSize));
        config.setPageSize(pageSize);
        List<SysUserResults> resultsList = oaSysUserMapper.sysUserListPaging(config);
        List<Long> sysUserIdList = new ArrayList<>();
        for (SysUserResults results : resultsList) {
            sysUserIdList.add(results.getSysUserId());
            if (CheckUtil.objIsNotEmpty(results.getBusinessModule())) {
                List<String> moduleIdList = new ArrayList<>();
                String[] modules = results.getBusinessModule().split(",");
                for (String m : modules) {
                    moduleIdList.add(m);
                }
                results.setBusinessTypeList(moduleIdList);
            }
            if (CheckUtil.objIsNotEmpty(results.getBusinessType())) {
                List<String> typeIdList = new ArrayList<>();
                String[] types = results.getBusinessType().split(",");
                for (String t : types) {
                    typeIdList.add(t);
                }
                results.setLevelList(typeIdList);
            }
        }
        List<OaSysDict> moduleDictList = getModuleDictList();
        List<OaSysDict> leveDictlList = getLevelDictList();
        List<OaSysUserRole> userRoleList = getUserRoleList(sysUserIdList);
        List<OaSysUserCity> userCityList = getUserCityList(sysUserIdList);
        List<OaSysArea> sysAreaList = getSysAreaList(userCityList);
        List<OaSysRole> sysRoleList = getSysRoleList(userRoleList);
        // 数据处理
        getDataProcessing(resultsList, moduleDictList, leveDictlList, userCityList, sysAreaList, userRoleList, sysRoleList);
        Map<String, Object> map = new HashMap<>(16);
        map.put("current", current);
        map.put("total", collectionList.size());
        map.put("size", pageSize);
        map.put("priceList", resultsList);
        return Rv.wrap(EErrorCode.success, map);
    }

    private List<SysUserResults> getDataProcessing(List<SysUserResults> resultsList, List<OaSysDict> moduleDictList, List<OaSysDict> leveDictlList,
                                                   List<OaSysUserCity> userCityList, List<OaSysArea> sysAreaList, List<OaSysUserRole> userRoleList, List<OaSysRole> sysRoleList) {
        for (SysUserResults results : resultsList) {
            results.setLoginFlagStr(ELoginFlag.findStatus(Integer.valueOf(results.getLoginFlag())).getDesc());
            String roleName = "";
            String cityName = "";
            String businessType = "";
            String businessModule = "";
            for (OaSysUserCity userCity : userCityList) {
                if (results.getSysUserId().equals(userCity.getUserId())) {
                    for (OaSysArea area : sysAreaList) {
                        if (userCity.getCityCode().equals(area.getAdCode())) {
                            if (StringUtils.isEmpty(cityName)) {
                                cityName = area.getName() + ",";
                            } else {
                                cityName = cityName + area.getName() + ",";
                            }
                        }
                    }
                }
            }
            for (OaSysUserRole userRole : userRoleList) {
                if (results.getSysUserId().equals(userRole.getUserId())) {
                    for (OaSysRole role : sysRoleList) {
                        if (userRole.getRoleId().equals(role.getRoleId())) {
                            if (StringUtils.isEmpty(roleName)) {
                                roleName = role.getName() + ",";
                            } else {
                                roleName = roleName + role.getName() + ",";
                            }
                        }
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(results.getBusinessTypeList())) {
                for (String type : results.getBusinessTypeList()) {
                    for (OaSysDict dict : moduleDictList) {
                        if (type.equals(dict.getValue())) {
                            if (StringUtils.isEmpty(businessModule)) {
                                businessModule = dict.getLabel() + ",";
                            } else {
                                businessModule = businessModule + dict.getLabel() + ",";
                            }
                        }
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(results.getLevelList())) {
                for (String level : results.getLevelList()) {
                    for (OaSysDict dict : leveDictlList) {
                        if (level.equals(dict.getValue())) {
                            if (StringUtils.isEmpty(businessType)) {
                                businessType = dict.getLabel() + ",";
                            } else {
                                businessType = businessType + dict.getLabel() + ",";
                            }
                        }
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(cityName)) {
                results.setCityName(cityName.substring(0, cityName.length() - 1));
            }
            if (CheckUtil.objIsNotEmpty(businessType)) {
                results.setBusinessType(businessType.substring(0, businessType.length() - 1));
            }
            if (CheckUtil.objIsNotEmpty(businessModule)) {
                results.setBusinessModule(businessModule.substring(0, businessModule.length() - 1));
            }
            if (CheckUtil.objIsNotEmpty(roleName)) {
                results.setRoleName(roleName.substring(0, roleName.length() - 1));
            }
        }
        return resultsList;
    }

    /**
     * 系统用户管理列表(获取已开通城市)
     *
     * @return
     */
    @Override
    public Rv getSysOpenCity() {
        List<OaSysOpenArea> openAreaList = new ArrayList<>();
        QueryWrapper<OaSysOpenArea> queryOpenArea = new QueryWrapper<>();
        queryOpenArea.eq(OaSysOpenArea.IS_OPNE, GlobalConfig.YES);
        openAreaList = oaSysOpenAreaMapper.selectList(queryOpenArea);
        return Rv.wrap(EErrorCode.success, openAreaList);
    }

    /**
     * 系统用户管理列表全部城市
     *
     * @return
     */
    @Override
    public Rv getSysAllCity() {
        List<OaSysOpenArea> openAreaList = new ArrayList<>();
        QueryWrapper<OaSysArea> queryOpenArea = new QueryWrapper<>();
        queryOpenArea.eq(OaSysArea.TYPE, ParameterEnum.THREE.getType());
        List<OaSysArea> areaList = oaSysAreaMapper.selectList(queryOpenArea);
        if (!areaList.isEmpty()) {
            for (OaSysArea area : areaList) {
                OaSysOpenArea open = new OaSysOpenArea();
                open.setCityId(area.getAdCode());
                open.setCityName(area.getName());
                openAreaList.add(open);
            }
        }
        return Rv.wrap(EErrorCode.success, openAreaList);
    }

    private List<OaSysDict> getModuleDictList() {
        QueryWrapper<OaSysDict> queryModuleDict = new QueryWrapper<>();
        queryModuleDict.eq(OaSysDict.TYPE, "business_module");
        return oaSysDictMapper.selectList(queryModuleDict);
    }

    private List<OaSysDict> getLevelDictList() {
        QueryWrapper<OaSysDict> queryLevelDict = new QueryWrapper<>();
        queryLevelDict.eq(OaSysDict.TYPE, "require_level");
        return oaSysDictMapper.selectList(queryLevelDict);
    }


    private List<OaSysUserRole> getUserRoleList(List<Long> sysUserId) {
        QueryWrapper<OaSysUserRole> queryUserRole = new QueryWrapper<>();
        queryUserRole.in(OaSysUserRole.USER_ID, sysUserId);
        return oaSysUserRoleMapper.selectList(queryUserRole);
    }

    private List<OaSysUserCity> getUserCityList(List<Long> sysUserId) {
        QueryWrapper<OaSysUserCity> queryUserCity = new QueryWrapper<>();
        queryUserCity.in(OaSysUserCity.USER_ID, sysUserId);
        return oaSysUserCityMapper.selectList(queryUserCity);
    }

    private List<OaSysRole> getSysRoleList(List<OaSysUserRole> userRoleList) {
        List<Long> roleList = new ArrayList<>();
        if (!userRoleList.isEmpty()) {
            for (OaSysUserRole role : userRoleList) {
                roleList.add(role.getRoleId());
            }
        }
        QueryWrapper<OaSysRole> querySysRole = new QueryWrapper<>();
        querySysRole.in(OaSysRole.ROLE_ID, roleList);
        return oaSysRoleMapper.selectList(querySysRole);
    }

    private List<OaSysArea> getSysAreaList(List<OaSysUserCity> userCityList) {
        List<String> cityCodeList = new ArrayList<>();
        List<OaSysArea> areaList = new ArrayList<>();
        if (!userCityList.isEmpty()) {
            for (OaSysUserCity city : userCityList) {
                cityCodeList.add(city.getCityCode());
            }
            QueryWrapper<OaSysArea> querySysArea = new QueryWrapper<>();
            querySysArea.in(OaSysArea.AD_CODE, cityCodeList);
            areaList = oaSysAreaMapper.selectList(querySysArea);
        }
        return areaList;
    }

    /**
     * 通过userId查询用户
     *
     * @param userId
     * @return
     */
    private OaCUserInfo getCUserByUserId(Long userId) {
        QueryWrapper<OaCUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCUserInfo.USER_ID, userId);
        OaCUserInfo oaCUserInfo = oaCUserInfoMapper.selectOne(queryWrapper);
        return oaCUserInfo;
    }

    /**
     * 通过userId查询司机
     *
     * @param userId
     * @return
     */
    private OaDUserInfo getDUserByUserId(Long userId) {
        QueryWrapper<OaDUserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaDUserInfo.DRIVER_ID, userId);
        OaDUserInfo oaDUserInfo = oaDUserInfoMapper.selectOne(queryWrapper);
        return oaDUserInfo;
    }

    /**
     * 获取用户、司机详情
     *
     * @return
     */
    @Override
    public Rv getUserDetails(OfficeParam officeParam) {
        // userType 1-用户 2-司机
        Integer userType = officeParam.getUserType();
        OaCUser cUser = null;
        OaDUser dUser = null;
        if (userType == 1) {
            cUser = oaCUserMapper.selectById(officeParam.getUserId());
        } else {
            dUser = oaDUserMapper.selectById(officeParam.getUserId());
        }
        if (CheckUtil.objIsEmpty(cUser) && CheckUtil.objIsEmpty(dUser)) {
            throw PangException.create(EErrorCode.noData);
        }
        UserResult result = new UserResult();
        // 用户
        if (CheckUtil.objIsNotEmpty(cUser)) {
            // 查询用户信息
            OaCUserInfo info = getCUserByUserId(cUser.getUserId());
            // 查询机构
            OaCUserOffice office = getCUserOffice(cUser.getUserId());
            if (CheckUtil.objIsNotEmpty(office)) {
                OaSysOffice userOffice = getSysOffice(office.getOfficeId());
                result.setOfficeId(userOffice.getOfficeId());
                result.setOfficeName(userOffice.getName());
            }
            userInfoDetails(result, info.getAge(), info.getNationality(), info.getUserLevel(), info.getBirthday(), info.getAddress(), info.getEmergencyContact(), info.getEmergencyMobile(),
                    info.getEmergencyAddress(), info.getIdentityPositiveFileId(), info.getIdentityOtherFileId(), info.getIdentityDueDate(), info.getIdentityNumber(), info.getIdentityType(),
                    info.getIdentityAddress(), info.getDriveLicenseFileId(), info.getDriveOtherLicenseFileId(), info.getDriveLicenseNo(), info.getDriverStartDate(), info.getDriveLicenseDuedate(),
                    info.getDriveLicenseType(), info.getDriveLicenseIssueplace(), info.getPassingDate(), info.getIdentityRefuseReason(), info.getIdriveRefuseReason(), info.getBlockedReason(),
                    info.getBlockedDate(), info.getAuditType(), info.getRegisterCityId());
            userDetails(result, cUser.getUserPhone(), cUser.getLoginAccount(), cUser.getUserName(), cUser.getNickName(), cUser.getAvatarFileId(),
                    cUser.getSex(), cUser.getEmail(), cUser.getIsBlocked(), cUser.getIdentityVerfied(), cUser.getDriveVerfied());
        }
        // 司机
        if (CheckUtil.objIsNotEmpty(dUser)) {
            OaDUserInfo info = getDUserByUserId(dUser.getDriverId());
            //查询机构
            OaDUserOffice office = getDUserOffice(dUser.getDriverId());
            if (CheckUtil.objIsNotEmpty(office)) {
                OaSysOffice userOffice = getSysOffice(Long.valueOf(office.getOfficeId()));
                result.setOfficeId(userOffice.getOfficeId());
                result.setOfficeName(userOffice.getName());
            }
            userInfoDetails(result, info.getAge(), info.getNationality(), info.getDriverLevel(), info.getBirthday(), info.getAddress(), info.getEmergencyContact(), info.getEmergencyMobile(),
                    info.getEmergencyAddress(), info.getIdentityPositiveFileId(), info.getIdentityOtherFileId(), info.getIdentityDueDate(), info.getIdentityNumber(), info.getIdentityType(),
                    info.getIdentityAddress(), info.getDriveLicenseFileId(), info.getDriveOtherLicenseFileId(), info.getDriveLicenseNo(), info.getDriverStartDate(), info.getDriveLicenseDuedate(),
                    info.getDriveLicenseType(), info.getDriveLicenseIssueplace(), info.getPassingDate(), info.getIdentityRefuseReason(), info.getIdriveRefuseReason(), info.getBlockedReason(),
                    info.getBlockedDate(), info.getAuditType(), info.getRegisterCityId());
            userDetails(result, dUser.getDriverPhone(), dUser.getLoginAccount(), dUser.getDriverName(), dUser.getNickName(), dUser.getAvatarFileId(),
                    dUser.getSex(), dUser.getEmail(), dUser.getIsBlocked(), dUser.getIdentityVerfied(), dUser.getDriveVerfied());
        }
        return Rv.wrap(EErrorCode.success, result);
    }

    public UserResult userDetails(UserResult result, String phone, String loginAccount, String name, String nickName, Long avatarFileId, String sex,
                                  String email, Integer isBlocked, Integer identityVerfied, Integer driveVerfied) {
        result.setPhone(phone);
        result.setLoginAccount(loginAccount);
        result.setName(name);
        result.setNickName(nickName);
        result.setAvatarFileId(avatarFileId);
        result.setSex(sex);
        result.setEmail(email);
        result.setIsBlocked(isBlocked);
        result.setIdentityVerfied(identityVerfied);
        result.setDriveVerfied(driveVerfied);
        return result;
    }

    public UserResult userInfoDetails(UserResult result, Integer age, Integer nationality, String userLevel, Date birthday, String address, String emergencyContact,
                                      String emergencyMobile, String emergencyAddress, Long identityPositiveFileId, Long identityOtherFileId, Date identityDueDate,
                                      String identityNumber, Integer identityType, String identityAddress, Long driveLicenseFileId, Long driveOtherLicenseFileId,
                                      String driveLicenseNo, Date driverStartDate, Date driveLicenseDuedate, String driveLicenseType, String driveLicenseIssueplace,
                                      Date passingDate, String identityRefuseReason, String idriveRefuseReason, String blockedReason, Date blockedDate,
                                      Integer auditType, Integer registerCityId) {
        result.setAge(age);
        result.setNationality(nationality);
        result.setUserLevel(userLevel);
        if (CheckUtil.objIsNotEmpty(birthday)) {
            result.setBirthday(oaDOrderCorrelationServiceImpl.getDateConversion(birthday));
        }
        if (CheckUtil.objIsNotEmpty(identityDueDate)) {
            result.setIdentityDueDate(oaDOrderCorrelationServiceImpl.getDateConversion(identityDueDate));
        }
        if (CheckUtil.objIsNotEmpty(driverStartDate)) {
            result.setDriverStartDate(oaDOrderCorrelationServiceImpl.getDateConversion(driverStartDate));
        }
        if (CheckUtil.objIsNotEmpty(driveLicenseDuedate)) {
            result.setDriveLicenseDuedate(oaDOrderCorrelationServiceImpl.getDateConversion(driveLicenseDuedate));
        }
        if (CheckUtil.objIsNotEmpty(passingDate)) {
            result.setPassingDate(oaDOrderCorrelationServiceImpl.getDateConversion(passingDate));
        }
        if (CheckUtil.objIsNotEmpty(blockedDate)) {
            result.setBlockedDate(oaDOrderCorrelationServiceImpl.getDateConversion(blockedDate));
        }
        result.setAddress(address);
        result.setEmergencyContact(emergencyContact);
        result.setEmergencyMobile(emergencyMobile);
        result.setEmergencyAddress(emergencyAddress);
        result.setIdentityPositiveFileId(identityPositiveFileId);
        result.setIdentityOtherFileId(identityOtherFileId);
        result.setIdentityNumber(identityNumber);
        result.setIdentityType(identityType);
        result.setIdentityAddress(identityAddress);
        result.setDriveLicenseFileId(driveLicenseFileId);
        result.setDriveOtherLicenseFileId(driveOtherLicenseFileId);
        result.setDriveLicenseNo(driveLicenseNo);
        result.setDriveLicenseType(driveLicenseType);
        result.setDriveLicenseIssueplace(driveLicenseIssueplace);
        result.setIdentityRefuseReason(identityRefuseReason);
        result.setIdriveRefuseReason(idriveRefuseReason);
        result.setBlockedReason(blockedReason);
        result.setAuditType(auditType);
        result.setRegisterCityId(registerCityId);
        return result;
    }

    /**
     * 通过ID查询用户机构
     *
     * @param userId
     * @return
     */
    private OaDUserOffice getDUserOffice(Long userId) {
        QueryWrapper<OaDUserOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaDUserOffice.DRIVER_ID, userId);
        OaDUserOffice oaDUserOffice = oaDUserOfficeMapper.selectOne(queryWrapper);
        return oaDUserOffice;
    }

    /**
     * 通过ID查询所在机构
     *
     * @param officeId
     * @return
     */
    private OaSysOffice getSysOffice(Long officeId) {
        QueryWrapper<OaSysOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysOffice.OFFICE_ID, officeId);
        OaSysOffice oaSysOffice = oaSysOfficeMapper.selectOne(queryWrapper);
        return oaSysOffice;
    }

    /**
     * 通过ID查询用户机构
     *
     * @param userId
     * @return
     */
    private OaCUserOffice getCUserOffice(Long userId) {
        QueryWrapper<OaCUserOffice> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaCUserOffice.USER_ID, userId);
        OaCUserOffice oaCUserOffice = oaCUserOfficeMapper.selectOne(queryWrapper);
        return oaCUserOffice;
    }

    /**
     * 管理员详情
     *
     * @return
     */
    @Override
    public Rv getSysUserDetails(OfficeParam officeParam) {
        Long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        Map<String, Object> resMap = new HashMap<>(16);
        SysUserResults results = new SysUserResults();
        Long[] officeParentIds = null;
        if (CheckUtil.objIsNotEmpty(officeParam.getUserId())) {
            OaSysUser sysUser = oaSysUserMapper.selectById(officeParam.getUserId());
            results.setSysUserId(officeParam.getUserId());
            results.setPhoto(sysUser.getPhoto());
            results.setNo(sysUser.getExpand4());
            results.setName(sysUser.getName());
            results.setLoginName(sysUser.getLoginName());
            results.setPassword("");
            results.setConfirmPassword("");
            results.setEmail(sysUser.getEmail());
            results.setPhone(sysUser.getPhone());
            results.setMobile(sysUser.getMobile());
            results.setLoginFlag(sysUser.getLoginFlag());
            results.setUserType(sysUser.getUserType());
            results.setLoginDate("");
            results.setCompanyName("");
            results.setOfficeName("");
            results.setSoftPhoneLoginUser(sysUser.getSoftPhoneLoginUser());
            results.setSoftPhoneLoginPassword(sysUser.getSoftPhoneLoginPassword());
            results.setSoftPhoneNumber(sysUser.getSoftPhoneNumber());
            if (CheckUtil.objIsNotEmpty(sysUser.getCompanyId())) {
                OaSysOffice company = oaSysOfficeMapper.selectById(sysUser.getCompanyId());
                results.setCompanyName(company.getName());
            }
            if (CheckUtil.objIsNotEmpty(sysUser.getOfficeId())) {
                // 查询机构
                OaSysOffice office = oaSysOfficeMapper.selectById(sysUser.getOfficeId());
                results.setOfficeName(office.getName());
                if (CheckUtil.objIsNotEmpty(office)) {
                    results.setOfficeId(office.getOfficeId());
                    results.setOfficeName(office.getName());
                    String[] officeIdsString = null;
                    officeIdsString = office.getParentIds().split(",");
                    officeParentIds = new Long[officeIdsString.length];
                    for (int idx = 0; idx < officeIdsString.length; idx++) {
                        officeParentIds[idx] = Long.parseLong(officeIdsString[idx]);
                    }
                }
            }
            if (CheckUtil.objIsNotEmpty(sysUser.getLoginDate())) {
                results.setLoginDate(DateFormatUtils.format(sysUser.getLoginDate(), "yyyy-MM-dd HH:mm:ss"));
            }
        }
        resMap.put("results", results);
        resMap.put("officeParentIds", officeParentIds);
        // 用户类型
        QueryWrapper<OaSysDict> typeQueryWrapper = new QueryWrapper<>();
        typeQueryWrapper.eq(OaSysDict.TYPE, "user_type").eq(OaSysDict.TAG, tag);
        List<OaSysDict> typeList = oaSysDictMapper.selectList(typeQueryWrapper);
        resMap.put("typeList", typeList);
        // 机构
        List<Map<String, Object>> officeMapList = new ArrayList<>();
        List<OaSysOffice> officeList = officeServiceImpl.getOfficeList(userId);
        officeMapList = ListToTreeUtil.getOfficeList(officeList, new ArrayList<>(), "");
        JSONArray officeResultList = ListToTreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(officeMapList)), "id", "pId", "children");
        resMap.put("officeList", officeResultList);
        // 处理角色
        List<UserRoleResult> roleResult = new ArrayList<>();
        processRole(roleResult, officeParam.getUserId());
        resMap.put("roleResult", roleResult);
        // 城市
        List<UserCityResult> cityResult = new ArrayList<>();
        processCity(cityResult, officeParam.getUserId());
        resMap.put("cityResult", cityResult);
        // 业务类型
        List<UserLevelResult> levelResult = new ArrayList<>();
        processLevel(levelResult, officeParam.getUserId());
        resMap.put("levelResult", levelResult);
        // 业务模块
        List<UserLevelResult> moduleResult = new ArrayList<>();
        processModule(moduleResult, officeParam.getUserId());
        resMap.put("moduleResult", moduleResult);
        return Rv.wrap(EErrorCode.success, resMap);
    }

    /**
     * 处理管理员详情城市
     *
     * @param cityResult
     * @param userId
     * @return
     */
    public List<UserCityResult> processCity(List<UserCityResult> cityResult, Long userId) {
        QueryWrapper<OaSysUserCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUserCity.USER_ID, userId);
        List<OaSysUserCity> oaSysUserCityList = oaSysUserCityMapper.selectList(queryWrapper);
        QueryWrapper<OaSysArea> allAreaWrapper = new QueryWrapper<>();
        allAreaWrapper.eq(OaSysArea.TYPE, ParameterEnum.THREE.getType());
        List<OaSysArea> allAreaList = oaSysAreaMapper.selectList(allAreaWrapper);
        UserCityResult result = new UserCityResult();
        if (!oaSysUserCityList.isEmpty()) {
            for (OaSysArea all : allAreaList) {
                result = new UserCityResult();
                result.setName(all.getName());
                result.setSelected(0);
                result.setCityCode(all.getAdCode());
                for (OaSysUserCity city : oaSysUserCityList) {
                    if (all.getAdCode().equals(city.getCityCode())) {
                        result.setSelected(1);
                    }
                }
                cityResult.add(result);
            }
        } else {
            for (OaSysArea all : allAreaList) {
                result = new UserCityResult();
                result.setName(all.getName());
                result.setSelected(0);
                result.setCityCode(all.getAdCode());
                cityResult.add(result);
            }
        }
        return cityResult;
    }

    /**
     * 处理管理员详情业务模块
     *
     * @param moduleResult
     * @param userId
     * @return
     */
    public List<UserLevelResult> processModule(List<UserLevelResult> moduleResult, Long userId) {
        OaSysUser sysUser = oaSysUserMapper.selectById(userId);
        UserLevelResult result = new UserLevelResult();
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "business_module");
        List<OaSysDict> oaSysDictList = oaSysDictMapper.selectList(queryWrapper);
        if (CheckUtil.objIsNotEmpty(sysUser) && CheckUtil.objIsNotEmpty(sysUser.getBusinessModule())) {
            String[] modules = sysUser.getBusinessModule().split(",");
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setName(all.getLabel());
                result.setValue(all.getValue());
                result.setSelected(0);
                for (String module : modules) {
                    if (all.getValue().equals(module)) {
                        result.setSelected(1);
                    }
                }
                moduleResult.add(result);
            }
        } else {
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setSelected(0);
                result.setName(all.getLabel());
                result.setValue(all.getValue());
                moduleResult.add(result);
            }
        }
        return moduleResult;
    }

    /**
     * 处理管理员详情业务类型
     *
     * @param levelResult
     * @param userId
     * @return
     */
    public List<UserLevelResult> processLevel(List<UserLevelResult> levelResult, Long userId) {
        OaSysUser sysUser = oaSysUserMapper.selectById(userId);
        UserLevelResult result = new UserLevelResult();
        QueryWrapper<OaSysDict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysDict.TYPE, "require_level");
        List<OaSysDict> oaSysDictList = oaSysDictMapper.selectList(queryWrapper);
        if (CheckUtil.objIsNotEmpty(sysUser) && CheckUtil.objIsNotEmpty(sysUser.getBusinessType())) {
            String[] types = sysUser.getBusinessType().split(",");
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setName(all.getLabel());
                result.setSelected(0);
                result.setValue(all.getValue());
                for (String type : types) {
                    if (all.getValue().equals(type)) {
                        result.setSelected(1);
                    }
                }
                levelResult.add(result);
            }
        } else {
            for (OaSysDict all : oaSysDictList) {
                result = new UserLevelResult();
                result.setName(all.getLabel());
                result.setSelected(0);
                result.setValue(all.getValue());
                levelResult.add(result);
            }
        }
        return levelResult;
    }

    /**
     * 处理管理员详情角色
     *
     * @param roleResult
     * @param userId
     * @return
     */
    public List<UserRoleResult> processRole(List<UserRoleResult> roleResult, Long userId) {
        // 查询角色
        QueryWrapper<OaSysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUserRole.USER_ID, userId);
        List<OaSysUserRole> oaSysUserRoleList = oaSysUserRoleMapper.selectList(queryWrapper);
        // 查询全部
        QueryWrapper<OaSysRole> allRoleWrapper = new QueryWrapper<>();
        List<OaSysRole> allRoleList = oaSysRoleMapper.selectList(allRoleWrapper);
        UserRoleResult result = new UserRoleResult();
        if (!oaSysUserRoleList.isEmpty()) {
            for (OaSysRole all : allRoleList) {
                result = new UserRoleResult();
                result.setName(all.getName());
                result.setSelected(0);
                result.setRoleId(all.getRoleId());
                for (OaSysUserRole role : oaSysUserRoleList) {
                    if (all.getRoleId().equals(role.getRoleId())) {
                        result.setSelected(1);
                    }
                }
                roleResult.add(result);
            }
        } else {
            for (OaSysRole all : allRoleList) {
                result = new UserRoleResult();
                result.setName(all.getName());
                result.setSelected(0);
                result.setRoleId(all.getRoleId());
                roleResult.add(result);
            }
        }
        return roleResult;
    }

    /**
     * 修改账号状态
     *
     * @return
     */
    @Override
    public Rv getUpdateSysUserStatus(OfficeParam officeParam) {
        if (CheckUtil.objIsEmpty(officeParam.getUserId())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        OaSysUser sysUser = oaSysUserMapper.selectById(officeParam.getUserId());
        if (sysUser.getLoginFlag().equals(GlobalConfig.YES)) {
            sysUser.setLoginFlag(GlobalConfig.NO);
        } else {
            sysUser.setLoginFlag(GlobalConfig.YES);
        }
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateUser(TokenUtil.getTokenUserId());
        oaSysUserMapper.updateById(sysUser);
        return Rv.wrap(EErrorCode.deleteSuccess);
    }

    /**
     * 管理员删除
     *
     * @return
     */
    @Override
    public Rv getDeleteSysUser(OfficeParam officeParam) {
        QueryWrapper<OaSysUser> deleteQueryWrapper = new QueryWrapper<>();
        deleteQueryWrapper.eq(OaSysUser.SYS_USER_ID, officeParam.getUserId());
        oaSysUserMapper.delete(deleteQueryWrapper);
        // 删除管理表
        QueryWrapper<OaSysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUserRole.USER_ID, officeParam.getUserId());
        oaSysUserRoleMapper.delete(queryWrapper);
        return Rv.wrap(EErrorCode.deleteSuccess);
    }

    /**
     * 管理员新增、修改
     *
     * @return
     */
    @Override
    public Rv getUpdateSysUser(SysUserParam sysUserParam) {
        Long userId = TokenUtil.getTokenUserId();
        String tag = TokenUtil.getTag();
        if (!sysUserParam.getPassword().equals(sysUserParam.getConfirmPassword())) {
            throw PangException.create(EErrorCode.passwordValidationError);
        }
        Date date = new Date();
        Long id = 0L;
        if (CheckUtil.objIsEmpty(sysUserParam.getOfficeId())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        Long companyId = iOfficeUtilService.getCompanyId(Long.valueOf(sysUserParam.getOfficeId()));
        // 新增
        if (CheckUtil.objIsEmpty(sysUserParam.getSysUserId())) {
            // 验证用户是否已存在
            Boolean userCheck = checkUserExist(sysUserParam);
            if (userCheck) {
                throw new PangException(EErrorCode.userExistError);
            }
            // 生成加密串
            Integer salt = RandomUtil.getRandomNumber(4);
            String passwordSalt = MD5Util.MD5(sysUserParam.getPassword() + salt);
            OaSysUser user = new OaSysUser();
            id = IDUtil.nextId();
            user.setTag(tag);
            user.setSysUserId(id);
            user.setCompanyId(companyId);
            user.setEmail(sysUserParam.getEmail());
            user.setLoginFlag(GlobalConfig.YES);
            user.setLoginName(sysUserParam.getLoginName());
            user.setMobile(sysUserParam.getMobile());
            user.setName(sysUserParam.getName());
            user.setNo(sysUserParam.getNo());
            user.setOfficeId(sysUserParam.getOfficeId());
            user.setPassword(passwordSalt);
            user.setPhone(sysUserParam.getPhone());
            user.setUserType(sysUserParam.getUserType());
            user.setUpdateUser(userId);
            user.setCreateUser(userId);
            user.setCreateTime(date);
            user.setUpdateTime(date);
            user.setSalt(salt);
            user.setBusinessModule(Joiner.on(",").join(sysUserParam.getModuleList()));
            user.setBusinessType(Joiner.on(",").join(sysUserParam.getLevelList()));
            user.setSoftPhoneLoginUser(sysUserParam.getSoftPhoneLoginUser());
            user.setSoftPhoneLoginPassword(sysUserParam.getSoftPhoneLoginPassword());
            user.setSoftPhoneNumber(sysUserParam.getSoftPhoneNumber());
            user.setExpand1(sysUserParam.getExpand1());
            user.setExpand2(sysUserParam.getExpand2());
            user.setExpand3(sysUserParam.getExpand3());
            user.setExpand4(sysUserParam.getExpand4());
            oaSysUserMapper.insert(user);
            OaSysUserOffice office = new OaSysUserOffice();
            office.setLinkedId(IDUtil.nextId());
            office.setCreateTime(date);
            office.setCreateUser(userId);
            office.setUpdateTime(date);
            office.setUpdateUser(userId);
            office.setOfficeId(Long.valueOf(sysUserParam.getOfficeId()));
            office.setSysUserId(id);
            office.setTag(tag);
            oaSysUserOfficeMapper.insert(office);
        }
        // 修改
        else {
            OaSysUser user = oaSysUserMapper.selectById(sysUserParam.getSysUserId());
            id = sysUserParam.getSysUserId();
            user.setBusinessModule(Joiner.on(",").join(sysUserParam.getModuleList()));
            user.setBusinessType(Joiner.on(",").join(sysUserParam.getLevelList()));
            user.setCompanyId(companyId);
            user.setEmail(sysUserParam.getEmail());
            user.setLoginName(sysUserParam.getLoginName());
            user.setMobile(sysUserParam.getMobile());
            user.setName(sysUserParam.getName());
            user.setNo(sysUserParam.getNo());
            user.setOfficeId(sysUserParam.getOfficeId());
            user.setSoftPhoneLoginUser(sysUserParam.getSoftPhoneLoginUser());
            user.setSoftPhoneLoginPassword(sysUserParam.getSoftPhoneLoginPassword());
            user.setSoftPhoneNumber(sysUserParam.getSoftPhoneNumber());
            if (StringUtils.isNotBlank(sysUserParam.getPassword())) {
                // 生成加密串
                Integer salt = RandomUtil.getRandomNumber(4);
                String passwordSalt = MD5Util.MD5(sysUserParam.getPassword() + salt);
                user.setPassword(passwordSalt);
                user.setSalt(salt);
            }
            user.setPhone(sysUserParam.getPhone());
            user.setUserType(sysUserParam.getUserType());
            user.setUpdateUser(userId);
            user.setUpdateTime(date);
            user.setTag(tag);
            user.setExpand1(sysUserParam.getExpand1());
            user.setExpand2(sysUserParam.getExpand2());
            user.setExpand3(sysUserParam.getExpand3());
            user.setExpand4(sysUserParam.getExpand4());
            oaSysUserMapper.updateById(user);
        }
        getUserRole(sysUserParam.getRoleList(), id);
        getUserCity(sysUserParam.getCityList(), id);
        return Rv.wrap(EErrorCode.updateSuccess);
    }

    /**
     * 检查用户是否已存在
     *
     * @param sysUserParam
     * @return
     */
    private Boolean checkUserExist(SysUserParam sysUserParam) {
        QueryWrapper<OaSysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUser.LOGIN_NAME, sysUserParam.getLoginName());
        List<OaSysUser> oaSysUserList = oaSysUserMapper.selectList(queryWrapper);
        if (CheckUtil.collectionIsEmpty(oaSysUserList)) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 处理关联角色
     *
     * @param roleList
     * @param id
     */
    public void getUserRole(List<Long> roleList, Long id) {
        QueryWrapper<OaSysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUserRole.USER_ID, id);
        oaSysUserRoleMapper.delete(queryWrapper);
        if (roleList != null && !roleList.isEmpty()) {
            OaSysUserRole role = null;
            for (int i = 0; i < roleList.size(); i++) {
                role = new OaSysUserRole();
                role.setRoleId(roleList.get(i));
                role.setUserId(id);
                oaSysUserRoleMapper.insert(role);
            }
        }
    }

    /**
     * 处理关联城市
     *
     * @param cityList
     * @param id
     */
    public void getUserCity(List<String> cityList, Long id) {
        QueryWrapper<OaSysUserCity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(OaSysUserCity.USER_ID, id);
        oaSysUserCityMapper.delete(queryWrapper);
        if (cityList != null && !cityList.isEmpty()) {
            OaSysUserCity city = null;
            for (int i = 0; i < cityList.size(); i++) {
                city = new OaSysUserCity();
                city.setCityCode(cityList.get(i));
                city.setUserId(id);
                oaSysUserCityMapper.insert(city);
            }
        }
    }

    @Override
    public Rv updateDriverManager(SysDriverManagerParam param) {
        OaSysArea area = oaSysAreaMapper.selectOne(Qw.create().eq(OaSysArea.AD_CODE, param.getCityId()));
        if (area == null) {
            return Rv.error(EErrorCode.noData);
        }
        //1.首选创建麒麟下属部门-以便于对数据进行管理
        UpdateOfficeParam officeParam = new UpdateOfficeParam();
        officeParam.setAreaId(String.valueOf(area.getAreaId()));
        officeParam.setAddress(area.getName());
        officeParam.setGrade(1);
        officeParam.setName(param.getName());
        officeParam.setType(1);
        officeParam.setSort("1");
        officeParam.setUseable("1");
        officeParam.setPhone(param.getPhone());
        officeParam.setParentId(param.getParentId());
        officeParam.setPrimaryPerson(param.getLeader());

        String userId = param.getId();
        Long muserId = null;
        if (CheckUtil.strIsNotEmpty(userId)) {
            muserId = Long.parseLong(userId);
            OaSysUserOffice office = oaSysUserOfficeMapper.selectOne(Qw.create().eq(OaSysUserOffice.SYS_USER_ID, userId));
            if (office != null) {
                officeParam.setOfficeId(office.getOfficeId());
            }
        }
        Rv officeRv = officeService.getUpdateOffice(officeParam);
        if (officeRv.getCode() != EErrorCode.success.getValue()) {
            return officeRv;
        }

        List<String> citys = new ArrayList<>();
        citys.add(area.getAdCode());

        List<Long> roles = new ArrayList<>();
        roles.add(1768999788642304L);//供应商角色ID

        List<String> levels = new ArrayList<>();
        levels.add("0");
        levels.add("1");
        levels.add("2");
        levels.add("3");

        List<String> modules = new ArrayList<>();
        modules.add("0");
        modules.add("1");

        //2.创建系统用户-用于供应商日常管理使用
        SysUserParam userParam = new SysUserParam();
        userParam.setSysUserId(muserId);
        userParam.setName(param.getName());
        userParam.setLoginName(param.getAccount());
        userParam.setPassword(param.getPassword());
        userParam.setConfirmPassword(param.getPassword());
        userParam.setMobile(param.getPhone());
        userParam.setCityList(citys);
        userParam.setOfficeId(officeParam.getOfficeId());
        userParam.setLevelList(levels);
        userParam.setRoleList(roles);
        userParam.setModuleList(modules);
        userParam.setExpand1(param.getLeader());//负责人姓名
        userParam.setExpand2(area.getAdCode());//城市编码
        userParam.setExpand3(param.getCode());//统一信用编码
        userParam.setExpand4(0);//司机数量

        return getUpdateSysUser(userParam);
    }

    @Override
    public Rv getSupplierSeparateAccount(SupplierSeparateAccountParam param) {
        if (CheckUtil.objIsEmpty(param.getLimit())) {
            // 若没有则默认显示十页
            param.setLimit(10L);
        }
        if (CheckUtil.objIsEmpty(param.getPage()) || CheckUtil.objIsEmpty(param.getLimit())) {
            throw PangException.create(EErrorCode.missingArg);
        }
        //这个可能会异常，数据不唯一
        try{
            //验证供应商用户是否存在
            QueryWrapper<OaSysUser> oaSysUserQueryWrapper = new QueryWrapper<>();
            oaSysUserQueryWrapper.eq(OaSysUser.SYS_USER_ID,param.getSysUserId());
            OaSysUser oaSysUser = oaSysUserMapper.selectOne(oaSysUserQueryWrapper);
            if(CheckUtil.objIsEmpty(oaSysUser)){
                Rv.error(EErrorCode.supplierUserIsNull);
            }
            //验证供应商是否存在
            QueryWrapper<OaSysOffice> oaSysOfficeQueryWrapper = new QueryWrapper<>();
            oaSysOfficeQueryWrapper.eq(OaSysOffice.OFFICE_ID,oaSysUser.getOfficeId());
            OaSysOffice oaSysOffice = oaSysOfficeMapper.selectOne(oaSysOfficeQueryWrapper);
            if(CheckUtil.objIsEmpty(oaSysOffice)){
                Rv.error(EErrorCode.supplierIsNull);
            }
        }catch (Exception e){
            Rv.error(EErrorCode.dataNoIsOne);
        }

        Page<OaSysUserSeparateAccount> page = new Page<>(param.getPage(), param.getLimit());
        QueryWrapper<OaSysUserSeparateAccount> qw = new QueryWrapper<>();
        qw.eq(OaSysUserSeparateAccount.SYS_USER_ID,param.getSysUserId());
        qw.eq(OaSysUserSeparateAccount.CITY_ID,param.getCityId());
        if(CheckUtil.objIsNotEmpty(param.getChannelId())){
            qw.eq(OaSysUserSeparateAccount.CHANNEL_ID,param.getChannelId());
        }
        qw.eq(OaSysUserSeparateAccount.DELETED,0);

        IPage<OaSysUserSeparateAccount> managers = oaSysUserSeparateAccountMapper.selectPage(page,qw);
        return Rv.wrap(managers);
    }

    @Override
    public Rv addOrUpdateSupplierSeparateAccount(List<OaSysUserSeparateAccount> param) {
        Long userId = TokenUtil.getTokenUserId();
        if(param.size() <= 0){
            Rv.error(EErrorCode.missingArg);
        }
        for (OaSysUserSeparateAccount info : param){
            //供应商用户id
            Long sysUserId = info.getSysUserId();
            OaSysUser oaSysUser = oaSysUserMapper.selectById(sysUserId);
            if(CheckUtil.objIsEmpty(oaSysUser)){
                Rv.error(EErrorCode.supplierUserIsNull);
            }
            Long separateAccountId = info.getSeparateAccountId();
            if(separateAccountId == null){//添加
                //验证一个城市一个渠道只能存在一条
                List<OaSysUserSeparateAccount> list = oaSysUserSeparateAccountMapper.selectList(Qw.create().eq(OaSysUserSeparateAccount.CITY_ID,info.getCityId())
                        .eq(OaSysUserSeparateAccount.CHANNEL_ID,info.getChannelId())
                        .eq(OaSysUserSeparateAccount.DELETED,0));
                if(list.size() > 0){
                    return Rv.error(EErrorCode.supplierSeparateAccountIsOne);
                }
                OaSysUserSeparateAccount newInfo = new OaSysUserSeparateAccount();
                newInfo.setSeparateAccountId(IDUtil.nextId());
                newInfo.setSysUserId(info.getSysUserId());
                newInfo.setUserName(info.getUserName());
                newInfo.setCityId(info.getCityId());
                newInfo.setLoginName(info.getLoginName());
                newInfo.setLeader(info.getLeader());
                newInfo.setMobile(info.getMobile());
                newInfo.setSeparateAccountRoleName(info.getSeparateAccountRoleName());
                newInfo.setChannelId(info.getChannelId());
                newInfo.setChannelProportion(info.getChannelProportion());
                newInfo.setQilinProportion(info.getQilinProportion());
                newInfo.setCpProportion(info.getCpProportion());
                newInfo.setDriverViolationProportion(info.getDriverViolationProportion());
                newInfo.setDriverWithdrawalProportion(info.getDriverWithdrawalProportion());
                newInfo.setDeleted(0);
                newInfo.setCreateUser(userId);
                newInfo.setUpdateUser(userId);
                newInfo.setCreateTime(new Date());
                newInfo.setUpdateTime(new Date());
                newInfo.setOfficeId(oaSysUser.getOfficeId());
                newInfo.setCompanyId(oaSysUser.getCompanyId());

                oaSysUserSeparateAccountMapper.insert(newInfo);
            }else {//更新
                OaSysUserSeparateAccount newInfo = new OaSysUserSeparateAccount();
                newInfo.setSeparateAccountId(info.getSeparateAccountId());
                newInfo.setSysUserId(info.getSysUserId());
                newInfo.setUserName(info.getUserName());
                newInfo.setCityId(info.getCityId());
                newInfo.setLoginName(info.getLoginName());
                newInfo.setLeader(info.getLeader());
                newInfo.setMobile(info.getMobile());
                newInfo.setSeparateAccountRoleName(info.getSeparateAccountRoleName());
                newInfo.setChannelId(info.getChannelId());
                newInfo.setChannelProportion(info.getChannelProportion());
                newInfo.setQilinProportion(info.getQilinProportion());
                newInfo.setCpProportion(info.getCpProportion());
                newInfo.setDriverViolationProportion(info.getDriverViolationProportion());
                newInfo.setDriverWithdrawalProportion(info.getDriverWithdrawalProportion());
                newInfo.setDeleted(info.getDeleted());//这个不能加删除注解
                newInfo.setUpdateUser(userId);
                newInfo.setUpdateTime(new Date());
                newInfo.setOfficeId(oaSysUser.getOfficeId());
                newInfo.setCompanyId(oaSysUser.getCompanyId());
                oaSysUserSeparateAccountMapper.updateById(newInfo);
            }
        }
        return Rv.wrap();
    }


    @Override
    public Rv getDriverManagers(SysDriverManagerParam param) {
        if (CheckUtil.objIsEmpty(param.getLimit())) {
            // 若没有则默认显示十页
            param.setLimit(10L);
        }

        if (CheckUtil.objIsEmpty(param.getPage()) || CheckUtil.objIsEmpty(param.getLimit())) {
            throw PangException.create(EErrorCode.missingArg);
        }

        IPage<OaSysUserManagersRes> page = new Page<>(param.getPage(), param.getLimit());
        /*
        QueryWrapper<OaSysUser> qw = new QueryWrapper<>();
        //1.供应商ID 2.供应商名称 3.管理员账号 4.负责人姓名 5.管理员手机号码 6.司机数量 7.所在城市
        qw.select(OaSysUser.SYS_USER_ID, OaSysUser.NAME, OaSysUser.LOGIN_NAME, OaSysUser.EXPAND1, OaSysUser.MOBILE, OaSysUser.EXPAND4, OaSysUser.EXPAND2);

        List<OaSysUserRole> roleList = oaSysUserRoleMapper.selectList(Qw.create().eq(OaSysRole.ROLE_ID, 1768999788642304L));
        List<Long> roleUserIds = new ArrayList<>();
        for (OaSysUserRole role : roleList) {
            roleUserIds.add(role.getUserId());
        }

        String name = param.getName();
        if (CheckUtil.strIsNotEmpty(name)) {
            qw.eq(OaSysUser.NAME, name);
        }
        String cityId = param.getCityId();
        if (CheckUtil.strIsNotEmpty(cityId)) {
            qw.eq(OaSysUser.EXPAND2, cityId);
        }

        qw.in(OaSysUser.SYS_USER_ID, roleUserIds);

        IPage<OaSysUser> managers = oaSysUserMapper.selectPage(page, qw);
        }*/
        List<OaSysUserManagersRes> offices = oaSysUserMapper.selectOfficesByConditions(page,param.getName(),param.getCityId());
        if(CheckUtil.objIsNotEmpty(offices)){
            page.setRecords(offices);
            return Rv.wrap(page);
        }
        return Rv.wrap();
    }
    @Override
    public Rv getDriverManagersByCity(String cityId) {
        //1.获取可查看系统用户
        long userId = TokenUtil.getTokenUserId();
        List<String> scopes = TokenUtil.getRoleDataScope();
        List<Long> sysUsers = oaSysGetOfficeIdListService.selectSysUserIdList(userId, scopes);

        //2.获取可查看供应商
        Qw roleQw = Qw.create();
        roleQw.eq(OaSysUserRole.ROLE_ID, 1768999788642304L);
        roleQw.in(OaSysUserRole.USER_ID, sysUsers);
        List<OaSysUserRole> roleList = oaSysUserRoleMapper.selectList(roleQw);
        StringBuffer roleUserIds = new StringBuffer();
        for (OaSysUserRole role : roleList) {
            roleUserIds.append(role.getUserId());
            roleUserIds.append(",");
        }
        roleUserIds.deleteCharAt(roleUserIds.length() - 1);

        List<Map<String, Object>> managers;
        if (CheckUtil.strIsEmpty(cityId)) {
            managers = oaSysUserMapper.getDriverManagers(roleUserIds.toString());
        } else {
            managers = oaSysUserMapper.getDriverManagersByCity(cityId, roleUserIds.toString());
        }
        return Rv.wrap(managers);
    }

    @Override
    public Rv getDriverManagerById(String id) {
        if (CheckUtil.strIsEmpty(id)) {
            return Rv.error(EErrorCode.argCheckErr);
        }
        QueryWrapper<OaSysUser> qw = new QueryWrapper<>();
        //1.供应商ID 2.供应商名称 3.管理员账号 4.负责人姓名 5.管理员手机号码 6.司机数量 7.所在城市 8.统一信用编码
        qw.select(OaSysUser.SYS_USER_ID, OaSysUser.COMPANY_ID, OaSysUser.NAME, OaSysUser.LOGIN_NAME, OaSysUser.EXPAND1, OaSysUser.MOBILE, OaSysUser.EXPAND4, OaSysUser.EXPAND2, OaSysUser.EXPAND3);
        qw.eq(OaSysUser.SYS_USER_ID, id);
        OaSysUser sysUser = oaSysUserMapper.selectOne(qw);
        return Rv.wrap(sysUser);
    }

    @Override
    public Rv getDriverByManager(String id,String vehicleTeam,String driverName,
                                 String driverPhone,String vehNo,Integer vehicleType) {
        if (CheckUtil.strIsEmpty(id)) {
            return Rv.error(EErrorCode.missingArg);
        }
        List<DUserInfoResult> driverInfos = oaDUserInfoMapper.getDriverInfo(id,vehicleTeam,driverName,driverPhone,vehNo,vehicleType);
        return Rv.wrap(driverInfos);
    }
}
